<template>
<!-- 头部信息渲染 Mr.huang satart -->
	<view class="container">
		<view class="header" :style="{ backgroundColor: '#67C23A' }">
		  <view class="nav-bar">
				<!-- 返回图标 -->
		    <view class="back" @click="goBack">
		      <uni-icons type="left" size="20" color="#FFFFFF"></uni-icons>
		    </view>
			  
			  <!-- 标题和评分 -->
		    <text class="title">{{ courseInfo.className }}</text>
		    <view class="right-area">
		    </view>
		  </view>
			
			<!-- 教师信息 -->
		  <view class="teacher-info">
		    <view>
				<!-- <image class="avatar" :src="courseInfo.teacherAvatar" mode="aspectFill" src="../../static/c1.png" /> -->
				<image class="avatar" mode="aspectFill" src="../../static/c1.png" />
			</view>
		    <view>
				<text class="name">{{ courseInfo.username }}</text>
			</view>
		    <view >
				<text class="time">{{ courseInfo.beginDate }}</text>
				<text class="time"> 至 </text>
				<text class="time">{{ courseInfo.endDate}}</text>
			</view>
		  </view>
			
			<!-- 课程进度 -->
		  <view class="week-info">
		    <text>当前：第{{ courseInfo.currentWeek }}/{{ courseInfo.totalWeek }}周</text>
		    <view class="student-count">
		      <uni-icons type="person" size="14" color="#FFFFFF"></uni-icons>
		      <text>{{ courseInfo.studentCount }}人</text>
		    </view>
		  </view>
		  <view class="progress-area">
		    <view class="progress-item">
		      <text>我的学习进度：</text>
		      <progress :percent="courseInfo.myProgress" stroke-width="3" activeColor="#FFFFFF" backgroundColor="rgba(255,255,255,0.3)" />
		    </view>
		    <view class="progress-item">
		      <text>平均学习进度：</text>
		      <progress :percent="courseInfo.avgProgress" stroke-width="3" activeColor="#FFFFFF" backgroundColor="rgba(255,255,255,0.3)" />
		    </view>
		  </view>
		</view>
<!-- 头部信息渲染 Mr.huang end -->

		<view class="tabs">
			<view v-for="(tab, index) in tabs" :key="index" class="tab-item" :class="{ active: currentTab === index }"
				@click="switchTab(index)">
				{{ tab }}
			</view>
		</view>

		<!-- 目录view -->
		<scroll-view v-if="currentTab === 0" scroll-y class="content">
			<!-- 模块列表 -->
			<view class="module-list">
				<view v-for="(module, moduleIndex) in courseModules" :key="moduleIndex" class="module-item">
					<view class="module-header" @click="toggleModule(moduleIndex)">
						<text class="module-title" :data-id="module.moduleId">{{ module.moduleName }}</text>
						<uni-icons :type="module.isExpanded ? 'top' : 'bottom'" size="14" color="#666"></uni-icons>
					</view>

					<!-- 课时列表 -->
					<!-- 判断其是否还能展开 -->
					<view v-if="module.isExpanded" class="lesson-list">
						<view v-for="(lesson, lessonIndex) in module.courseHourList" :key="lessonIndex"
							class="lesson-item">
							<view class="lesson-header" @click="toggleLesson(moduleIndex, lessonIndex)">
								<view class="lesson-dot"></view>
								<text class="lesson-title" :data-id="lesson.courseHourId" >{{ lesson.courseName }}</text>
								<uni-icons :type="lesson.isExpanded ? 'top' : 'bottom'" size="14"
									color="#666"></uni-icons>
							</view>

							<!-- 资源列表 -->
							<view v-if="lesson.isExpanded && lesson.resourceList" class="resource-list">
								<view v-for="(resource, resourceIndex) in lesson.resourceList" :key="resourceIndex"
									class="resource-item" @click="openResource(resource.resourceId,resource.resourceName)">
									<uni-icons type="file" size="16" color="#666"></uni-icons>
									<text class="resource-name"
										:data-id="resource.resourceId" :data-resourceName="resource.resourceName" >{{ resource.resourceName }}</text>
									<text class="resource-pages">{{ resource.pageCount }}页</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<!-- 目录view 结束 -->

		<!-- yh 修改过此地方的内容 -->
		<scroll-view v-else-if="currentTab === 2" scroll-y class="content">
			<view class="classroom-list">
				<view class="filter-bar">
					<text>筛选</text>
					<uni-icons type="funnel" size="16" color="#666"></uni-icons>
				</view>
				<text v-if="flog === 0">还没有课程</text>
				<view v-for="(classroom, index) in classrooms" :key="index" class="classroom-item">
					<view class="classroom-info">
						<text class="classroom-date">课堂{{ classroom.classroomName }}</text>
						<text class="classroom-status" :class="classroom.status">{{ classroom.statusText }}</text>
					</view>
					<view class="classroom-detail">
						<text class="label">授课教师：</text>
						-
						<text class="value">{{ classroom.user.username }}</text>
					</view>
					<view class="classroom-detail">
						<text class="label">上课时间：</text>
						<text class="value">{{ classroom.beginDate }}</text>
					</view>
					<view class="classroom-actions">
						<button class="enter-btn" :class="{ disabled: classroom.status !== 'ongoing' }" @click="enterClassroom(classroom)">
							进入课堂
						</button>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
	import { ref, onMounted } from 'vue';

	const tabs = ref(['目录', '签到', '课堂', '能力考核', '直播', '任务', '公告']);
	const currentTab = ref(0);
	
	/* 头部信息渲染 start */
	// 定义一个响应式变量来存储课程信息
	const courseInfo = ref(null);
	 
	// 组件挂载后获取数据
	const loadHeaderInfo = async (id) => {
	  try {
	    const res = uni.request({
			url: `http://192.168.100.54:8080/header/info?classId=${id}`,
			method: 'GET',
			success: (response) => {
				// 假设服务器返回的数据在 response.data 中
				courseInfo.value = response.data.t[0];
			},
		});
	  } catch (error) {
	    console.error('请求异常:', error);
	  }
	};
		
	// 返回上一页
	const goBack = () => {
	  uni.reLaunch({ url: '/pages/index/index' })
	}

	/* 头部信息渲染 end */

	const courseModules = ref([]);
	const classrooms = ref([]);//yh 修改
	const flog = ref(0); //yh 添加
	

	const loadCourseModules = async (id) => {
		try {
			const res = await uni.request({
				url: 'http://192.168.100.54:8080/catalog/showClassCatalog',
				method: 'GET',
				data: { id }
			});

			if (res.data.code === 200) {
				courseModules.value = res.data.t.map(module => ({
					...module,
					isExpanded: false,
					courseHourList: module.courseHourList.map(hour => ({
						...hour,
						isExpanded: false
					}))
				}));
				console.log('目录加载成功', courseModules.value);
			} else {
				uni.showToast({
					title: '目录加载失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('加载目录失败:', error);
			uni.showToast({
				title: '加载目录失败',
				icon: 'none'
			});
		}
	};

	const toggleModule = (moduleIndex) => {
		courseModules.value[moduleIndex].isExpanded = !courseModules.value[moduleIndex].isExpanded;
	};

	const toggleLesson = (moduleIndex, lessonIndex) => {
		courseModules.value[moduleIndex].courseHourList[lessonIndex].isExpanded = !courseModules.value[moduleIndex]
			.courseHourList[lessonIndex].isExpanded;
	};
	
	const openResource = (id,resourceName) => {
	  if (id) {
	    // 跳转到预览页面
		console.log("===============>编号" + id);
	    uni.reLaunch({
			url:'/pages/study/file-preview?id='+id+ "&resourceName="+resourceName
	    })
	  } else {
	    uni.showToast({
	      title: '获取资源失败',
	      icon: 'none'
	    });
	  }
	};

// yh修改
	const switchTab = (index) => {
		currentTab.value = index;
	
		if (index == 2) {
			console.log("index==" + index);
			fetchClassList();
		}
	};
	//
	const enterClassroom = (classroom) => {
		if (classroom.status !== 'ongoing') {
			uni.showToast({
				title: '课堂未开始或已结束',
				icon: 'none'
			});
			return;
		}
		console.log(classroom.id);
		uni.reLaunch({
			// console.log("10.2");
			// console.log("classroom.id="+classroom.id);
			url: '/pages/study/classroom-page?classId='+classroom.id
		});
	};
	
	//yh 添加？？？？ 查看课堂
	const fetchClassList = async () => {
		try {
			const res = await uni.request({
				url: 'http://localhost:8080/classRoom/classList?classId=1',
				method: 'GET'
			});
	
			if (res.statusCode === 200) {
				console.log('响应数据:', res.data.t); // 打印服务器返回的数据
				flog.value = 0;
				if (classrooms.value.length !== 0) {
					flog.value = 1;
				}
	
				// 处理数据并添加新字段
				classrooms.value = res.data.t.map(item => {
					let statusText;
					let status;
					if (item.status == '进行中') {
						statusText = '进行中';
						status = "ongoing";
					} else if (item.status == '已结束') {
						statusText = '已结束';
						status = "finished";
					} else if (item.status == '未开始') {
						statusText = '未开始';
						status = "upcoming";
					}
	
					return {
						...item, // 保留原有的所有字段
						statusText: statusText, // 添加新字段 statusText
						status: status // 添加新字段 status
					};
				});
	
				console.log(classrooms.value.length); // 打印数组长度
	
				// 如果需要进一步处理或打印数据
				for (let i = 0; i < classrooms.value.length; i++) {
					console.log(classrooms.value[i].endDate);
					console.log(classrooms.value[i].statusText);
					console.log(classrooms.value[i].status);
				}
			} else {
				console.error('请求失败：', res);
			}
		} catch (err) {
			console.error('请求发生错误：', err);
		}
	};
	
	// 钩子函数 （公共资源）
	onMounted(() => {
		
		// 获取当前页面实例
		 const pages = getCurrentPages();
		 const currentPage = pages[pages.length - 1];
		 const options = currentPage.options;
				
		 // 获取 id 参数
		 const id = options.id;
		 console.log('111111111111111',id);
		
		  // 调用 loadHeaderInfo 函数并传递 id 参数
		  if (id) {
			  
			// 加载头部信息
		    loadHeaderInfo(id);
			
			// 加载目录
			loadCourseModules(id);
			
		  } else {
		    console.error('未找到 id 参数');
		    uni.showToast({
		      title: '未找到 id 参数',
		      icon: 'none'
		    });
		  }
		
		
		
		// 在组件创建时调用fetchClassList方法
		fetchClassList();
	});
</script>

<style lang="scss">
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	.header {
		padding: 40px 20rpx 30rpx;
		color: #FFFFFF;
		background-color: #67C23A;

		.nav-bar {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 30rpx;

			.title {
				font-size: 34rpx;
				font-weight: 500;
			}

			.right-area {
				display: flex;
				align-items: center;

				.score {
					margin-right: 20rpx;
				}
			}
		}

		.teacher-info {
			display: flex;
			align-items: center;
			margin-bottom: 20rpx;

			.avatar {
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				overflow: hidden;
				margin-right: 20rpx;
			}

			.name {
				font-size: 28rpx;
				margin-right: 20rpx;
			}

			.time {
				font-size: 24rpx;
				opacity: 0.8;
			}
		}

		.week-info {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;
			font-size: 26rpx;

			.student-count {
				display: flex;
				align-items: center;

				text {
					margin-left: 6rpx;
				}
			}
		}

		.progress-area {
			.progress-item {
				margin-bottom: 16rpx;

				text {
					font-size: 24rpx;
					margin-bottom: 8rpx;
					display: block;
				}

				&:last-child {
					margin-bottom: 0;
				}
			}
		}
	}

	.content {
		height: calc(100vh - 400rpx);
	}

	.module-list {
		padding: 20rpx;

		.module-item {
			background-color: #FFFFFF;
			border-radius: 12rpx;
			margin-bottom: 20rpx;
			overflow: hidden;
		}

		.module-header {
			padding: 24rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			background-color: #f8f8f8;

			.module-title {
				font-size: 30rpx;
				font-weight: 500;
			}
		}
	}

	.lesson-list {
		.lesson-item {
			border-bottom: 1rpx solid #eee;

			&:last-child {
				border-bottom: none;
			}
		}

		.lesson-header {
			padding: 20rpx 24rpx;
			display: flex;
			align-items: center;

			.lesson-dot {
				width: 8rpx;
				height: 8rpx;
				border-radius: 50%;
				background-color: #67C23A;
				margin-right: 12rpx;
			}

			.lesson-title {
				flex: 1;
				font-size: 28rpx;
			}
		}
	}

	.resource-list {
		padding: 0 24rpx 20rpx 44rpx;

		.resource-section {
			margin-bottom: 16rpx;

			&:last-child {
				margin-bottom: 0;
			}

			.section-title {
				font-size: 26rpx;
				color: #999;
				margin-bottom: 12rpx;
			}
		}

		.resource-item {
			display: flex;
			align-items: center;
			padding: 12rpx 0;

			.resource-name {
				flex: 1;
				font-size: 26rpx;
				color: #333;
				margin: 0 12rpx;
			}

			.resource-pages {
				font-size: 24rpx;
				color: #999;
			}
		}
	}

	.tabs {
		display: flex;
		background-color: #FFFFFF;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #eee;

		.tab-item {
			flex: 1;
			text-align: center;
			font-size: 28rpx;
			color: #666;
			position: relative;

			&.active {
				color: #67C23A;
				font-weight: 500;

				&::after {
					content: '';
					position: absolute;
					bottom: -20rpx;
					left: 50%;
					transform: translateX(-50%);
					width: 40rpx;
					height: 4rpx;
					background-color: #67C23A;
				}
			}
		}
	}

	.classroom-list {
		padding: 20rpx;

		.filter-bar {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			padding: 20rpx;
			color: #666;
			font-size: 26rpx;

			.uni-icons {
				margin-left: 6rpx;
			}
		}

		.classroom-item {
			background-color: #FFFFFF;
			border-radius: 12rpx;
			padding: 24rpx;
			margin-bottom: 20rpx;

			.classroom-info {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 16rpx;

				.classroom-date {
					font-size: 32rpx;
					font-weight: 500;
				}

				.classroom-status {
					font-size: 26rpx;

					&.ongoing {
						color: #67C23A;
					}

					&.upcoming {
						color: #E6A23C;
					}

					&.finished {
						color: #909399;
					}
				}
			}

			.classroom-detail {
				display: flex;
				font-size: 26rpx;
				margin-bottom: 12rpx;

				.label {
					color: #999;
					width: 140rpx;
				}

				.value {
					color: #333;
					flex: 1;
				}
			}

			.classroom-actions {
				display: flex;
				justify-content: flex-end;
				margin-top: 20rpx;

				.enter-btn {
					background-color: #67C23A;
					color: #FFFFFF;
					font-size: 26rpx;
					padding: 12rpx 30rpx;
					border-radius: 6rpx;

					&.disabled {
						background-color: #C0C4CC;
					}
				}
			}
		}
	}
</style>